<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Area as areaModel;
use app\admin\model\Product as productModel;
use app\admin\model\News as newsModel;
use app\admin\model\About as aboutModel;
use app\admin\model\Project as projectModel;
use app\admin\model\Down as downModel;
use app\admin\validate\Area as areaValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Area extends Base{
    // 列表
    public function index(){
        $from = input('from'); $keyword = input('keyword'); $order = ['sequence'=>'desc','id'=>'desc'];
        // 来源模板
		switch ($from) {
		    case 'viewlist':
		        $template = 'viewlist';
		        break;
		    case 'citylist':
		        $template = 'citylist';
		        break;
		    default:
		        $template = '';
		        break;
		}
		
		$rs = areaModel::index($this->lang,12,$keyword,$order,$from);
		
        View::assign('list',$rs);
        View::assign('total',$rs->total());
        View::assign('lastPage',$rs->lastPage());
        
        return view($template);
    }

    // 添加编辑
    public function edit($id=0){
        $rs = areaModel::find($id);
        View::assign('rs',$rs);
        if(!request()->isPost()){
			// 父级标题
            $parent_title = '';
            if(!empty($rs)){
                $sortRs = Db::name('area')->field('title')->where('id',$rs['parentid'])->find();
                $parent_title = $sortRs['title'];
            }
            View::assign('parent_title',$parent_title);
            
            /*模板列表 开始*/
            $skinPath = request()->server('DOCUMENT_ROOT').'/skin/index/';
            if(!is_dir($skinPath)) $this->error(lang('v_template').lang('g_not_existed'));
            
            $dofile = new \common\Dofile();
            $list = $dofile->getFiles($skinPath,false,'jpg');
            asort($list);
            View::assign(['list' => $list]);
            /*模板列表 结束*/

            return view();
        }else{
            // 表单验证
            try {
                validate(areaValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1001, 'msg' => $e->getMessage(), 'data' => '']);
            }
            
            // 不能和语言目录相同，防止二级域名冲突
            $langRs = Db::name('language')->where('mulu',input('urlroute'))->field('mulu')->find();
            if(!empty($langRs)) return json(['code' => 1002, 'msg' => lang('c_area_urlroute'), 'data' => $langRs]);
            
            // 判断绑定的域名是否已经存在
            $configDomainArray = config('app.domain_bind'); $bind_domain = input('bind_domain');
            if(input('is_domain') == 1 and !empty($bind_domain) and array_key_exists($bind_domain,$configDomainArray) and $rs['bind_domain'] != $bind_domain){
                return json(['code' => 1003, 'msg' => lang('v_bind_domain_existed'), 'data' => $bind_domain]);
            }
            if(stripos($bind_domain,'.') == 0 and !empty($bind_domain)){
                return json(['code' => 1004, 'msg' => lang('v_bind_domain_existed'), 'data' => $bind_domain]);
            }
            // 判断域名是否合法
            $domain_preg = "/^(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}$/";  
            // if(!preg_match($domain_preg,$bind_domain)){
            //     return json(['code' => 1005, 'msg' => lang('v_domain').lang('g_illegal'), 'data' => $bind_domain]);
            // }

			try {
                areaModel::edit($id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
	}
	
	// 单条删除
    public function delete_one(){
		$id = input('id');
        // 禁止删除默认地区
        if(in_array($id, array('1','2'))) return json(['code' => 1001, 'msg' => lang('c_fail'), 'data' => array('id'=>$id)]);
        // 禁止删除含有子项的父项
        $hasChild = Db::name('area')->where('parentid',$id)->find();
        if(!empty($hasChild)) return json(['code' => 1002, 'msg' => lang('c_delete_sort_child_first'), 'data' => $hasChild]);

        try {
            Db::name('area')->delete($id);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	/* 批量删除，返回值：
    @ error:no_check 未勾选数据
    @ success 成功
    */
    public function delete_all(){
		$selectid = input('selectid/a');
		if(empty($selectid)) return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
		
		foreach($selectid as $i => $rs){
		    $id = $selectid[$i];
            // 禁止删除默认地区
            if(in_array($id, array('1','2'))){
                return json(['code' => 1002, 'msg' => lang('c_fail'), 'data' => array('id'=>$id)]);
                break;
            }
            // 禁止删除含有子项的父项
            $hasChild = Db::name('area')->where('parentid',$id)->find();
            if(!empty($hasChild)){
                return json(['code' => 1003, 'msg' => lang('c_delete_sort_child_first'), 'data' => $hasChild]);
                break;
            }
            $deleteid[] = $id;
	    }

		try {
            Db::name('area')->delete($deleteid);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 批量更新
    public function update_all(){
		$id = input('id/a'); $sequence = input('sequence/a');
        
		foreach($id as $i => $rs){
            $data[] = ['id'=>$id[$i],'sequence'=>$sequence[$i]];
        }

		try {
            $area = new areaModel;
            $area->saveAll($data,true);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
}